package com.hyt.it.ogt.kq.service.gov.service.impl;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.hyt.it.ogt.kq.common.config.exception.KqException;
import com.hyt.it.ogt.kq.common.gov.constant.ResponseCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyt.core.base.BaseServiceImpl;
import com.hyt.core.util.UUIDUtils;
import com.hyt.it.ogt.kq.common.gov.constant.CodeEnum;
import com.hyt.it.ogt.kq.service.gov.mapper.ExamAreaMapper;
import com.hyt.it.ogt.kq.service.gov.model.entity.ExamArea;
import com.hyt.it.ogt.kq.service.gov.model.vo.ExamAreaParamVO;
import com.hyt.it.ogt.kq.service.gov.service.IExamAreaService;
import com.hyt.it.ogt.kq.service.gov.service.ITaskConfigService;
import com.hyt.model.PageParam;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * 考区信息表 服务实现类
 * </p>
 *
 * @author huangyh
 * @since 2021-03-08
 */
@Service
public class ExamAreaServiceImpl extends BaseServiceImpl<ExamAreaMapper, ExamArea> implements IExamAreaService {

    @Resource
    private ITaskConfigService iTaskConfigService;
    
    @Resource
    private ExamAreaMapper examAreaMapper;

    @Override
    public Page<ExamArea> getExamArea(PageParam<ExamArea> pageParam, String taskId, String searchTxt) {

        Page<ExamArea> examAreaPage = examAreaMapper.selectExamAreaGroupByExamAreaCode(pageParam, taskId, searchTxt);
        if(Objects.nonNull(examAreaPage) && !CollectionUtils.isEmpty(examAreaPage.getRecords())){
            List<ExamArea> areas = examAreaPage.getRecords();
            List<ExamArea> newAresa = areas.stream().sorted(Comparator.comparing(ExamArea::getUpdateDate).reversed())
                    .collect(Collectors.toList());
            examAreaPage.setRecords(newAresa);
        }
        return examAreaPage;
    }

	@Override
	public List<ExamArea> getArea(String taskId, String examAreaCode) {
		return examAreaMapper.selectArea(taskId, examAreaCode, CodeEnum.AREA_TYPE_PROVINCE.getCode().toString());
	}

	@Override
	public List<ExamArea> getStudentArea(String taskId, String examAreaCode) {
		return examAreaMapper.selectStudentArea(taskId, examAreaCode, CodeEnum.AREA_TYPE_PROVINCE.getCode().toString());
	}
	
    @Override
    public void removeExamArea(String taskId, String examAreaCode) {

        LambdaUpdateWrapper<ExamArea> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
        lambdaUpdateWrapper.eq(ExamArea::getTaskId,taskId)
                .eq(ExamArea::getExamAreaCode,examAreaCode)
                .eq(ExamArea::getDelFlag,false)
                .set(ExamArea::getDelFlag,true);
        this.update(lambdaUpdateWrapper);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrUpdateExamArea(ExamAreaParamVO examAreaParamVO) {
        String taskId = examAreaParamVO.getTaskId();
        //重新添加考区
        String[] areas = examAreaParamVO.getAreaCodes().split(",");

        //更新操作
        if (StringUtils.isNotBlank(examAreaParamVO.getExamAreaCode())) {
            //先判断是否有重复的
            LambdaQueryWrapper<ExamArea> queryArea = Wrappers.lambdaQuery();
            queryArea.eq(ExamArea::getDelFlag,Boolean.FALSE);
            queryArea.eq(ExamArea::getTaskId,taskId);
            queryArea.ne(ExamArea::getExamAreaCode,examAreaParamVO.getExamAreaCode());
            queryArea.in(ExamArea::getAreaCode, Arrays.asList(areas));
            if(this.count(queryArea) > 0){
                throw new KqException(ResponseCode.EXAM_AREA_ADD_UPDATE_REPECT.getCode(),ResponseCode.EXAM_AREA_ADD_UPDATE_REPECT.getMsg());
            }

            LambdaUpdateWrapper<ExamArea> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
            lambdaUpdateWrapper.eq(ExamArea::getTaskId,examAreaParamVO.getTaskId())
                    .eq(ExamArea::getExamAreaCode,examAreaParamVO.getExamAreaCode())
                    .eq(ExamArea::getDelFlag,false)
                    .set(ExamArea::getDelFlag,true);
            this.update(lambdaUpdateWrapper);
        } else {
            //现在新增操作，处理一下是否有重复
            //先判断是否有重复的
            LambdaQueryWrapper<ExamArea> queryArea = Wrappers.lambdaQuery();
            queryArea.eq(ExamArea::getDelFlag,Boolean.FALSE);
            queryArea.eq(ExamArea::getTaskId,taskId);
            queryArea.in(ExamArea::getAreaCode, Arrays.asList(areas));
            if(this.count(queryArea) > 0){
                throw new KqException(ResponseCode.EXAM_AREA_ADD_UPDATE_REPECT.getCode(),ResponseCode.EXAM_AREA_ADD_UPDATE_REPECT.getMsg());
            }
        }

        List<ExamArea> examAreaList = new ArrayList<>();

        for (int i = 0; i < areas.length; i++) {
            String areaCode = areas[i];
           String examAreaCode = UUIDUtils.newSortUUID();

            String[] studentAreas = examAreaParamVO.getStudentAreaCodes().split(",");
            for (int j = 0; j < studentAreas.length; j++) {
                String studentCode = studentAreas[j];
                ExamArea examArea = new ExamArea();
                examArea.setExamAreaName(examAreaParamVO.getExamAreaName())
                        .setExamAreaCode(examAreaCode)
                        .setTaskId(examAreaParamVO.getTaskId())
                        .setAreaCode(areaCode)
                        .setAreaName(examAreaMapper.selectAreaOneName(examAreaParamVO.getTaskId(),areaCode))
                        .setRemark(examAreaParamVO.getRemark())
                        .setStudentAreaCode(studentCode)
                        .setStudentAreaName(examAreaMapper.selectStudentAreaOneName(examAreaParamVO.getTaskId(),studentCode))
                        .setUpdateDate(LocalDateTime.now())
                        .setCreateDate(LocalDateTime.now())
                        .setId(UUIDUtils.newSortUUID());

                examAreaList.add(examArea);
            }
        }

        //批量更新
        this.saveBatch(examAreaList);

    }

    @Override
    public void copyExamArea(String oldTaskId, String newTaskId, String userName) {
    	examAreaMapper.copyExamArea(oldTaskId, newTaskId, userName);
    }

}
